set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO

--发票审核 1=财,2=转,3=银
CREATE procedure [dbo].[sp_jiuqi_fpinput_list_xsfy] @kpid int,@isignseq int output,@csign varchar(100) output

AS


declare @note varchar(100),@custid int,@compid int,@iszb int
select @compid=dbo.gf_sys_cwcompid_by_compid(compid),@custid=custid from t_cw_kp where kpid=@kpid

select @iszb=isnull(iszb,0) from t_sys_comp where compid=@compid
select @isignseq=dbo.gf_cw_sys_isignseq(@compid,2)
select @csign=dbo.gf_cw_sys_csign(dbo.gf_sys_cwcompid_by_compid(@compid),@isignseq)


select @note='应付'+
             (select b.name from t_jiuqi_supplier_mapping a inner join t_cw_cust b on a.supplier_id=b.custid where a.company_id=@compid and a.supplier_id=@custid)--select b.name from t_u8_vendor a inner join t_cw_cust b on a.custid=b.custid where a.compid=@compid and a.custid=@custid)
             +'销售费用'

declare @jsje numeric(18,2),@taxje numeric(18,2)
select @jsje=sum(je1),@taxje=sum(taxje) from t_wl_ykp where kpid=@kpid

declare @ccode2 varchar(100),@ccname2 varchar(100)

--进项税科目
declare @u8code varchar(100)
select top 1 @u8code=b.feeu8code from t_cw_wlfy a,t_cw_feetype b where a.kpid=@kpid and a.ftid1=b.ftid and a.taxje>0

select @ccode2=@u8code,
  @ccname2=(select ccode_name from t_cw_sys_code where compid=@compid and ccode=@u8code)


--禁止存在两个税科目
if (select count(distinct b.ftid) from t_cw_wlfy a,t_cw_feetype b where a.kpid=@kpid and a.ftid1=b.ftid and a.taxje>0)>1
  select @ccname2='',@ccode2=''


select
  note=@note,
  ccode=b.k3code,
  ccname=dbo.gf_cw_sys_code_name(dbo.gf_sys_cwcompid_by_compid(c.compid),b.k3code),
  md=isnull(a.je1,0)-isnull(a.taxje,0),
  mc=0.00,
  ismd=1,
  ismc=0,
  ccus_id=null,
  csup_id=null,
  isadd=0,
  isdept=1,
  isproc=0
from t_wl_ykp a
  inner join t_cw_feetype b on a.ftid1=b.ftid
  inner join t_cw_kp c on a.kpid=c.kpid
where a.kpid=@kpid

union all

select
  note=@note,
  ccode=@ccode2,
  ccname=@ccname2,
  md=@taxje,
  mc=0.00,
  ismd=1,
  ismc=0,
  ccus_id=null,
  csup_id=null,
  isadd=0,
  isdept=0,
  isproc=0
where isnull(@taxje,0)<>0

union all

select
  note=@note,
  ccode=(select code from t_jiuqi_common_subject_code where company_id=@compid and code_id=400),--select u8code from t_u8_code where compid=@compid and codeid=400),
  ccname=(select dbo.gf_cw_sys_code_name(@compid,code) from t_jiuqi_common_subject_code where company_id=@compid and code_id=400),--select dbo.gf_cw_sys_code_name(@compid,u8code) from t_u8_code where compid=@compid and codeid=400),
  md=0,
  mc=@jsje,
  ismd=0,
  ismc=1,
  ccus_id=null,
  csup_id=(select code from t_jiuqi_supplier_mapping where company_id=@compid and supplier_id=@custid),--select u8code from t_u8_vendor where compid=@compid and custid=@custid),
  isadd=0,
  isdept=0,--(case when @iszb=1 then 1 else 0 end),
  isproc=0
























